package cServer

import (
	"context"
	"fmt"
	"net"
	"reflect"

	"google.golang.org/grpc"

	"gitee.com/csingo/cCommon"
	"gitee.com/csingo/cContext"
	"gitee.com/csingo/cLog"
)

func startGRPC() {
	if !server_config.GrpcServer.Enable {
		return
	}

	// 监听端口
	conn, err := net.Listen("tcp", fmt.Sprintf(":%d", server_config.GrpcServer.Port))
	if err != nil {
		cLog.WithContext(nil, map[string]interface{}{
			"source": "cServer.startGRPC",
			"err":    err.Error(),
		}, []cLog.Option{
			cLog.IncludePaths{},
		}).Fatal("GRPC 服务端口监听异常")
	}

	// 注册路由
	server := grpc.NewServer(grpc.UnaryInterceptor(newRouteUnaryServerInterceptor()))
	container.Range(func(instance any) {
		if reflect.TypeOf(instance).Implements(reflect.TypeOf((*GrpcServiceInterface)(nil)).Elem()) {
			desc := instance.(GrpcServiceInterface).GrpcServiceDesc()
			server.RegisterService(desc, instance)
		}
	})

	cLog.WithContext(nil, map[string]interface{}{
		"source": "cServer.startGRPC",
		"port":   server_config.GrpcServer.Port,
	}, []cLog.Option{
		cLog.IncludePaths{},
	}).Info("启动 GRPC 服务")

	// 启动服务
	if err = server.Serve(conn); err != nil {
		cLog.WithContext(nil, map[string]interface{}{
			"source": "cServer.startGRPC",
			"err":    err.Error(),
		}, []cLog.Option{
			cLog.IncludePaths{},
		}).Fatal("GRPC 服务启动失败")
	}
}

func newRouteUnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
		// context 转换为 gin.Context
		newCtx := cContext.GrpcToGin(ctx)
		newCtx.Set(cCommon.XIndex_RequestType, "GRPC")
		// 处理service
		resp, err = handler(newCtx, req)
		if err != nil {
			return
		}
		newCtx.Set(cCommon.XIndex_ResponseData, resp)
		return
	}
}
